package com.example.ymm.modules1.service.impl.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.my.user.DbDept;
import com.example.ymm.modules1.mapper.my.user.DbDeptMapper;
import com.example.ymm.modules1.service.dd.DdUserServer;
import com.example.ymm.modules1.service.dto.DbDeptQueryCriteria;
import com.example.ymm.modules1.service.dto.ImportDeptExcelDto;
import com.example.ymm.modules1.service.user.DbDeptService;
import com.example.ymm.modules1.service.user.DbDeptUserService;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@DSTransactional
@DS("master")
@Slf4j
public class DbDeptServiceImpl extends BaseServiceImpl<DbDeptMapper, DbDept> implements DbDeptService {


    @Autowired
    DdUserServer ddUserServer;

    @Autowired
    DbDeptUserService dbDeptUserService;

    @Override
    public TableList<DbDept> list(DbDeptQueryCriteria criteria, YmPageDto pageDto) {
        IPage<DbDept> page = new Page<DbDept>(pageDto.getPage(),pageDto.getPageSize());
        baseMapper.selectPage(page, QueryHelpPlus.getPredicate(DbDept.class, criteria));
        TableList<DbDept> tableList=new TableList(page);
        return tableList;
    }

    public List<DbDept> queryAll(DbDeptQueryCriteria criteria) {
        QueryWrapper predicate = QueryHelpPlus.getPredicate(DbDept.class, criteria);
        predicate.orderByAsc("sort");
        List<DbDept> result =baseMapper.selectList(predicate);
        return result;
    }


    @Override
    public List<DbDept> getDeptTreeList(DbDeptQueryCriteria criteria) {
        List<DbDept> dbDepts = queryAll(criteria);
        List<DbDept> result=new ArrayList<>();
        dbDepts.forEach(e->{
            e.setTitle(e.getName());
            if(UtilValidate.isEmpty(e.getParentId())){
                forEachDeptList(e,dbDepts);
                result.add(e);
            }
        });
        return result;
    }

    @Override
    public void syncUpLoad() {
       // log.info("----开始同步部门信息--");
        JSONArray allDeptList = ddUserServer.getAllDeptList();
        dbDeptUserService.removeByAll();
        for (int i = 0; i < allDeptList.size(); i++) {
            JSONObject jsonObject = allDeptList.getJSONObject(i);
            forEachDeptList(jsonObject,"1",i);
        }
        log.info("----部门信息同步完成--");

    }

    public DbDept syncByJson(JSONObject json,String parentId,int sort){
        DbDept dbDept=null;
        String dept_id= json.getString("dept_id");
        DbDept dept = getById(dept_id);
        if(UtilValidate.isNotEmpty(dept)){
            dbDept=dept;
            JSONObject ext= json.getJSONObject("ext");
            if(UtilValidate.isNotEmpty(ext)){
                Integer faceCount = ext.getInteger("faceCount");
                if(UtilValidate.isNotEmpty(dbDept.getCount())&&UtilValidate.isNotEmpty(faceCount)){
                    if(!dbDept.getCount().equals(faceCount)){
                        dbDept.setCount(faceCount);
                        saveOrUpdate(dbDept);
                    }
                }

            }

        }else{
            dbDept=new DbDept();
            dbDept.setDeptId(dept_id);
            dbDept.setName(json.getString("name"));
            JSONObject ext= JSON.parseObject(json.getString("ext"));
            if(UtilValidate.isNotEmpty(ext)&& ext.containsKey("faceCount")){
                dbDept.setCount(ext.getInteger("faceCount"));
            }
            dbDept.setParentId(parentId);
            dbDept.setSort(sort);
            saveOrUpdate(dbDept);
        }
        return dbDept;
    }

    public void forEachDeptList(DbDept parent,List<DbDept> list){

        List<DbDept> children=new ArrayList<>();
        list.forEach(e->{
            if(parent.getDeptId().equals(e.getParentId())){
                children.add(e);
            }
        });

        if(UtilValidate.isNotEmpty(children)){
            children.sort(new Comparator<DbDept>() {
                @Override
                public int compare(DbDept o1, DbDept o2) {
                    return o1.getSort()-o2.getSort();
                }
            });
            parent.setChildren(children);

            children.forEach(r->{
                forEachDeptList(r,list);
            });
        }

    }

    public void forEachDeptList(JSONObject item,String parentId,int sort){
        if(UtilValidate.isNotEmpty(item)){
            //同步部门
            DbDept dbDept = syncByJson(item, parentId, sort);
            //同步人员
            Long dept_id = item.getLong("dept_id");
            JSONObject deptUserJson = ddUserServer.getDeptUserList(dept_id);
            dbDeptUserService.syncByJson(deptUserJson,dbDept);

            JSONArray children = item.getJSONArray("children");
            if(UtilValidate.isNotEmpty(children)){
                for (int i = 0; i < children.size(); i++) {
                    JSONObject jsonObject = children.getJSONObject(i);
                    forEachDeptList(jsonObject,dbDept.getDeptId(),i);
                }
            }
        }


    }


    @Override
    public List<String> findDeptIdToParentIdList(String deptId) {
        DbDept dept = getById(deptId);
        if(UtilValidate.isEmpty(dept)){
            List<String> result=new ArrayList<>();
            return result;
        }
        StringBuffer s=new StringBuffer();
        s.append(deptId);
        if(!"-1".equals(dept.getParentId())){
            forEachParentId(dept.getParentId(),s);
        }

        String[] split = s.toString().split(",");
        return Arrays.asList(split);
    }

    public void forEachParentId(String parentId,StringBuffer s){
//        DbDeptQueryCriteria criteria=new DbDeptQueryCriteria();
//        criteria.setParentId(parentId);
        DbDept dbDept = getById(parentId);
//        List<DbDept> dbDepts = queryAll(criteria);
        if(UtilValidate.isNotEmpty(dbDept)){
            s.append(","+dbDept.getDeptId());
            if(!"0".equals(dbDept.getParentId())){
                forEachParentId(dbDept.getParentId(),s);
            }

        }
    }


    @Override
    public List<Map<String, Object>> importDepts(ImportDeptExcelDto dto) {
        List<DbDept> list = dto.getList();
        List<Map<String,Object>> ms=new ArrayList<>();
        for(int a=0;a<list.size();a++) {
            DbDept dept = list.get(a);
            StringBuffer buffer = new StringBuffer();
            if (UtilValidate.isEmpty(dept.getName()) && UtilValidate.isEmpty(dept.getDeptId())) {
                continue;
            }
            if(UtilValidate.isEmpty(dept.getName())){
                buffer.append("部门名称不能为空");
            }
            if(UtilValidate.isEmpty(dept.getDeptId())){
                buffer.append(" 部门id不能为空");
            }
            if(UtilValidate.isNotEmpty(buffer.toString())){
                Map<String,Object> map=new HashMap<>();
                map.put("index",a+1+2);
                map.put("message",buffer.toString());
                ms.add(map);
            }
        }
        if(UtilValidate.isEmpty(ms)){
            //删除所有部门数据
            LambdaQueryWrapper<DbDept> queryWrapper=new LambdaQueryWrapper<>();
            remove(queryWrapper);
            List<DbDept> batchList=new ArrayList<>();
            for(int a=0;a<list.size();a++){
                DbDept dept = list.get(a);
                dept.setSort(a);
                if (UtilValidate.isEmpty(dept.getName()) && UtilValidate.isEmpty(dept.getDeptId())) {
                    continue;
                }
                batchList.add(dept);
            }
            saveOrUpdateBatch(batchList);
        }
        return ms;
    }
}
